<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>动画函数的封装</title>
		<style type="text/css">
			* {
				margin: 0;
				padding: 0;
				box-sizing: border-box;
			}
			div {
				position: absolute;
				top: 50px;
				left: 0;
				width: 200px;
				height: 200px;
				background-color: pink;
			}
		</style>
	</head>
	<body>
		<button>点击才开始移动</button>
		<div>
			
		</div>
		<script type="text/javascript">
			window.addEventListener('load',function() {
				//封装添动画函数
				function animute(obj,target){
					//先清除之前的定时器，确保只有一个定时器在运行
					
					clearInterval(obj.timer);
					//obj是元素对象,target是目标位置
					obj.timer = setInterval(function() { 	//使用obj.name来区别定时器,能够减少内存的浪费
						if(obj.offsetLeft >= target){
							clearInterval(obj.timer)
						}
						//获取元素的宽度,给元素设置left的值
						obj.style.left = obj.offsetLeft + 1 + 'px';
					},30)
				}
				var div = document.querySelector('div');
				var btn = document.querySelector('button')
				btn.addEventListener('click',function() {
					animute(div,400)
				})
				
			})
		</script>
	</body>
</html>
